﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SCMS.Model;
using System.Data;
using System.Data.Objects.DataClasses;
using SCMS.CoreBusinessLogic.NotificationsManager;
using SCMS.CoreBusinessLogic.OrderRequest;
using System.Transactions;
using SCMS.Utils.DTOs;

namespace SCMS.CoreBusinessLogic.TenderAnalysis
{
    public class TAnalysisService : ITAnalysisService
    {
        private INotificationService NotificationService;
        private IOrderRequest ORequestService;

        public TAnalysisService(INotificationService NotificationService, IOrderRequest ORequestService)
        {
            this.NotificationService = NotificationService;
            this.ORequestService = ORequestService;
        }

        public bool SaveTAnalysis(Model.TenderAnalysi entity)
        {
            using (var db = new SCMSEntities())
            {
                entity.POToBeIssued = false;
                entity.SupplierSelected = false;
                entity.CurrencyId = db.OrderRequests.FirstOrDefault(p => p.Id == entity.OrderRequestId).CurrencyId;
                var ta = db.TenderAnalysis.FirstOrDefault(t => t.Id == entity.Id && t.CountryProgrammeId == entity.CountryProgrammeId);
                if (ta != null)
                {
                    entity.Id = ta.Id;
                    db.TenderAnalysis.Attach(entity);
                    db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
                }
                else
                {
                    if (entity.Id.Equals(Guid.Empty))
                        entity.Id = Guid.NewGuid();
                    db.TenderAnalysis.AddObject(entity);
                }
                if (db.SaveChanges() > 0 && (bool)entity.IsSubmitted)
                {
                    NotificationService.SendNotification(NotificationService.GetApproverEmailAddress(1, NotificationHelper.taCode), NotificationHelper.taMsgBody, NotificationHelper.tasubject);
                    return true;
                }
                else return false;
            }
        }

        public void AuthorizeTA(Model.TenderAnalysi ta)
        {
            using (var context = SCMSEntities.Define())
            {
                context.TenderAnalysis.Attach(ta);
                context.ObjectStateManager.ChangeObjectState(ta, EntityState.Modified);
                context.SaveChanges();
            }
        }

        public bool SaveTBidder(Model.TenderBidder entit, List<Model.TenderBidderQuote> TBQuotes)
        {
            using (var db = new SCMSEntities())
            {
                var ta = db.TenderAnalysis.First(p => p.Id == entit.TenderAnalysisId);
                //first check if that supplier already exists in this TA
                var tbdr = db.TenderBidders.FirstOrDefault(t => t.TenderAnalysisId == ta.Id && t.SupplierId == entit.SupplierId);
                if (tbdr != null)
                {
                    entit.Id = tbdr.Id;
                    entit.EntityKey = tbdr.EntityKey;
                    db.Detach(tbdr);
                    db.Attach(entit);
                    db.ObjectStateManager.ChangeObjectState(entit, EntityState.Modified);
                    //Get existing tender bidder quotes and delete them
                    var tbqList = db.TenderBidderQuotes.Where(t => t.TenderBidderId == entit.Id).ToList();
                    foreach (var tbq in tbqList)
                        db.TenderBidderQuotes.DeleteObject(tbq);
                    //effect changes
                    db.SaveChanges();
                    foreach (Model.TenderBidderQuote item in TBQuotes)
                        item.TenderBidderId = tbdr.Id;
                }
                else
                    db.TenderBidders.AddObject(entit);

                foreach (Model.TenderBidderQuote item in TBQuotes)
                    db.TenderBidderQuotes.AddObject(item);
                db.ObjectStateManager.ChangeObjectState(ta, System.Data.EntityState.Modified);
                return (db.SaveChanges() > 0) ? true : false;
            }
        }

        public bool DeleteTenderBidder(Guid tbId)
        {
            using (var context = SCMSEntities.Define())
            {
                var tb = context.TenderBidders.FirstOrDefault(t => t.Id == tbId);
                if (tb != null)
                {
                    context.TenderBidders.DeleteObject(tb);
                    return context.SaveChanges() > 0 ? true : false;
                }
            }
            return false;
        }

        public bool SaveEvaluators(Model.TenderEvaluator entity)
        {
            using (var db = new SCMSEntities())
            {
                if (entity.Id == Guid.Empty)
                {
                    entity.Id = Guid.NewGuid();
                    db.TenderEvaluators.AddObject(entity);
                }
                else
                {
                    db.TenderEvaluators.Attach(entity);
                    db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
                }               

                return (db.SaveChanges() > 0) ? true : false;
            }
        }

        public bool DeleteTenderEvaluator(Guid teId)
        {
            using (var db = new SCMSEntities())
            {
                var eval = db.TenderEvaluators.FirstOrDefault(t => t.Id == teId);
                if (eval != null)
                {
                    db.TenderEvaluators.DeleteObject(eval);
                    return db.SaveChanges() > 0 ? true : false;
                }
            }
            return false;
        }

        public void SaveTenderAnalysis(TenderAnalysi ta)
        {
            using (var context = new SCMSEntities())
            {
                context.TenderAnalysis.Attach(ta);
                context.ObjectStateManager.ChangeObjectState(ta, EntityState.Modified);
                context.SaveChanges();
            }
        }

        public Model.TenderAnalysi GetTenderAnalysisEntity(Guid id)
        {
            using (var db = new SCMSEntities())
            {
                Model.TenderAnalysi TA = db.TenderAnalysis.SingleOrDefault(p => p.Id == id);
                Staff s = TA.Staff1; Designation dd = s.Designation; 
                Person pp = s.Person;
                Model.Currency curr = TA.OrderRequest.Currency;
                return TA;
            }
        }

        public Model.Item GetItemName(Guid id)
        {
            using (var db = new SCMSEntities())
            {
                return db.OrderRequestItems.SingleOrDefault(p => p.Id == id).Item;
            }
        }

        public List<Model.TenderAnalysi> Search(Model.TenderAnalysi entity)
        {
            using (var dbContext = new SCMSEntities())
            {
                List<Model.TenderAnalysi> TAList = dbContext.TenderAnalysis.Where(p => p.RefNumber.Contains(entity.RefNumber)).OrderByDescending(p => p.PreparedOn).ToList();
                foreach (TenderAnalysi item in TAList)
                {
                    Model.OrderRequest or = item.OrderRequest;
                }
                return TAList;
            }
        }

        public string GenerateUniqueNumber(CountryProgramme cp)
        {
            string code = "TAE/DRC/" + cp.Country.ShortName + "/";
            string refNumber = "";
            long count = 1;
            using (var dbContext = new SCMSEntities())
            {
                var total = dbContext.TenderAnalysis.Where(p => p.CountryProgrammeId == cp.Id && p.IsSubmitted == true).Count();
                count = total;
                Model.TenderAnalysi m = null;
                do
                {
                    count++;
                    if (count < 10000)
                    {
                        if (count < 10)
                            refNumber = code + "0000" + count;
                        if (count < 100 & count >= 10)
                            refNumber = code + "000" + count;
                        if (count < 1000 & count >= 100)
                            refNumber = code + "00" + count;
                        if (count < 10000 & count >= 1000)
                            refNumber = code + "0" + count;
                    }
                    m = dbContext.TenderAnalysis.FirstOrDefault(p => p.RefNumber == refNumber);
                } while (m != null);
                return refNumber;
            }
        }

        public List<Model.TenderAnalysi> GetTenderColl(Guid countryProgId)
        {
            using (var context = new SCMSEntities())
            {
                List<Model.TenderAnalysi> tenders = new List<TenderAnalysi>();
                tenders = context.TenderAnalysis.Where(p => p.CountryProgrammeId == countryProgId).OrderByDescending(p => p.PreparedOn).ToList();
                foreach (TenderAnalysi item in tenders)
                {
                    var or = item.OrderRequest;
                    var person = item.Staff1.Person;
                }
                return tenders;
            }
        }

        public List<Model.TenderBidder> GetTenderBidderColl(Guid TAID)
        {
            using (var context = new SCMSEntities())
            {
                List<TenderBidder> TBs = new List<TenderBidder>();
                //TenderAnalysi TA = context.TenderAnalysis.SingleOrDefault(p => p.OrderRequestId == TAID);
                //if (TA == null)
                //    return new List<TenderBidder>();
                //TBs = context.TenderBidders.Where(C => C.TenderAnalysisId == TA.Id).ToList();
                TBs = context.TenderBidders.Where(C => C.TenderAnalysisId == TAID).OrderBy(t => t.Supplier.Name).ToList();
                foreach (TenderBidder item in TBs)
                {
                    ShippingTerm st = item.ShippingTerm;
                    Supplier s = item.Supplier;
                    PaymentTerm pt = item.PaymentTerm;
                }
                return TBs;
            }
        }

        public List<Model.TenderBidderQuote> GetTenderBidderQuoteColl(Guid TenderBidderId)
        {
            using (var context = new SCMSEntities())
            {
                List<TenderBidderQuote> TBQs = new List<TenderBidderQuote>();
                TBQs = context.TenderBidderQuotes.Where(p => p.TenderBidderId == TenderBidderId).OrderBy(t => t.OrderRequestItem.Item.Name).ToList();
                foreach (TenderBidderQuote item in TBQs)
                {
                    OrderRequestItem ORI = item.OrderRequestItem;
                    Item it = ORI.Item;
                }
                return TBQs;
            }
        }

        public List<Model.OrderRequest> GetOrderRequests(Guid countryProgId, string orId = "")
        {
            List<Model.OrderRequest> orderRequests = new List<Model.OrderRequest>();
            using (var context = new SCMSEntities())
            {
                var orList = new List<Model.OrderRequest>();
                if (orId == "")
                {
                    orList = context.OrderRequests.Where(p => p.IsAuthorized == true && p.CountryProgrammeId == countryProgId
                        && p.TenderAnalysis.Where(t => t.IsRejected == false && t.TenderBidders.Count() == 0).Count() == 0).OrderByDescending(p => p.OrderDate).ToList();
                }
                else
                {
                    var orderRequestId = new Guid(orId);
                    orList = context.OrderRequests.Where(p => p.IsAuthorized == true && p.CountryProgrammeId == countryProgId
                        && (p.TenderAnalysis.Where(t => t.IsRejected == false && t.TenderBidders.Count() == 0).Count() == 0 
                        || p.Id == orderRequestId)).OrderByDescending(p => p.OrderDate).ToList();
                }
                foreach (var or in orList)
                {
                    if (HasUnProcessedItems(or) || (orId != "" && or.Id == new Guid(orId)))
                    {
                        var curr = or.Currency;
                        var pd = or.ProjectDonor;
                        orderRequests.Add(or);
                    }
                }
                return orderRequests;
            }
        }
 
        /// <summary>
        /// This method checks if an Order Request still has items that have not been added to a Tender Analysis or Purchase Order
        /// Its aim is to prevent order request items from being added to more than one TA or PO
        /// </summary>
        /// <param name="or"></param>
        /// <returns></returns>
        private bool HasUnProcessedItems(Model.OrderRequest or)
        {
            using (var context = new SCMSEntities())
            {
                bool hasUnprocessedItems = false;
                //Get list of or items that haven't been added to any TA
                var unprocessedOrItems = context.OrderRequestItems.Where(o => o.OrderRequestId == or.Id && o.TenderBidderQuotes.Where(t => t.TenderBidder.TenderAnalysi.IsRejected == false).Count() == 0).ToList();
                //Loop through that list to see if any has not been added to a PO. If we find any then we have at least one un processed or item. 
                foreach (OrderRequestItem orItem in unprocessedOrItems)
                {
                    if (orItem.PurchaseOrderItems.Where(p => p.PurchaseOrder.IsRejected == false).Count() == 0)
                    {
                        hasUnprocessedItems = true;
                        break;
                    }
                }
                return hasUnprocessedItems;
            }
        }

        public List<Model.OrderRequestItem> GetUnprocessedORItems(Guid orId)
        {
            using (var context = new SCMSEntities())
            {
                var unprocessedOrItems = context.OrderRequestItems.Where(o => o.OrderRequestId == orId && o.TenderBidderQuotes.Where(t => t.TenderBidder.TenderAnalysi.IsRejected == false).Count() == 0
                    && o.PurchaseOrderItems.Where(p => p.PurchaseOrder.IsRejected == false).Count() == 0).ToList();
                foreach (var orItem in unprocessedOrItems)
                {
                    var item = orItem.Item;
                    var curr = orItem.OrderRequest.Currency;
                }
                return unprocessedOrItems;
            }
        }

        public List<Model.VStaffDetail> GetStaffs(Guid id)
        {
            using (var context = new SCMSEntities())
            {
                return context.VStaffDetails.Where(p => p.CountryProgrammeId == id).OrderBy(s => s.StaffName).ToList();
                //DataTable staff = new DataTable();
                //staff.Columns.Add("Id",typeof(Guid));
                //staff.Columns.Add("Name", typeof(string));
                //DataRow Row = null;
                //foreach (Staff item in st)
                //{
                //    //Person p = item.Person;
                //    //Designation d = item.Designation;

                //    Row = staff.NewRow();
                //    staff.Rows.Add(Row);
                //    Row[0] = item.Id;
                //    Row[1] = item.Person.FirstName + " " + item.Person.OtherNames;
                //}
                //return staff;
            }
        }

        public List<Model.StaffView> GetStaffForTAEvaluation(Guid cpId, Guid taId)
        {
            using (var context = new SCMSEntities())
            {
                return (from e in context.Staffs
                        where !(from t in context.TenderEvaluators
                                where t.TenderAnalysisId == taId
                                select t.StaffId).Contains(e.Id)
                                && e.CountrySubOffice.CountryProgrammeId == cpId
                        select new StaffView
                        {
                            Id = e.Id,
                            StaffId = e.Id,
                            StaffName = e.Person.FirstName + " " + e.Person.OtherNames,
                            StaffDesignation = e.Designation.Name
                        }).OrderBy(s => s.StaffName).ToList<StaffView>();
            }
        }

        public List<Model.StaffView> GetStaffForTAEvaluation(Guid cpId, Guid taId, Guid StaffId)
        {
            using (var context = new SCMSEntities())
            {
                return (from e in context.Staffs
                        where !(from t in context.TenderEvaluators
                                where (t.TenderAnalysisId == taId && t.StaffId != StaffId)
                                select t.StaffId).Contains(e.Id)
                                && e.CountrySubOffice.CountryProgrammeId == cpId
                        select new StaffView
                        {
                            Id = e.Id,
                            StaffId = e.Id,
                            StaffName = e.Person.FirstName + " " + e.Person.OtherNames,
                            StaffDesignation = e.Designation.Name
                        }).OrderBy(s => s.StaffName).ToList<StaffView>();
            }
        }

        public List<Model.OrderRequestItem> GetOrderRequestItems(Guid TAid)
        {
            using (var context = new SCMSEntities())
            {
                Guid ORID = context.TenderAnalysis.FirstOrDefault(p => p.Id == TAid).OrderRequestId;
                List<Model.OrderRequestItem> list = context.OrderRequestItems.Where(p => p.OrderRequestId == ORID).OrderBy(o => o.Item.Name).ToList();
                foreach (OrderRequestItem item in list)
                {
                    Item i = item.Item;
                }
                return list;
            }
        }

        public List<Model.Supplier> GetSuppliers(Guid countryProgId)
        {
            using (var context = SCMSEntities.Define())
            {
                return context.Suppliers.Where(s => s.CountryProgrammeId == countryProgId).OrderBy(s => s.Name).ToList();
            }
        }

        public List<Model.Supplier> GetSuppliers(Guid TAid, Guid countryProgId)
        {
            using (var context = new SCMSEntities())
            {
                var suppliers = (from s in context.Suppliers
                                 where !(from b in context.TenderBidders
                                         where b.TenderAnalysisId == TAid
                                         select b.SupplierId).Contains(s.Id)
                                 select s).Where(s => s.CountryProgrammeId == countryProgId).ToList<Supplier>();

                return suppliers;
            }
        }

        public List<Model.Supplier> GetSuppliers(Guid taId, Guid cpId, Guid tbId)
        {
            try
            {
                using (var context = SCMSEntities.Define())
                {
                    var suppliers = (from s in context.Suppliers
                                     where !(from b in context.TenderBidders
                                             where b.TenderAnalysisId == taId && b.Id != tbId
                                             select b.SupplierId).Contains(s.Id)
                                     select s).Where(s => s.CountryProgrammeId == cpId).ToList<Supplier>();

                    return suppliers;
                }
            }
            catch (Exception ex)
            {
                return new List<Supplier>();
            }
        }

        public TenderBidder GetTenderBidderById(Guid Id)
        {
            using (var context = SCMSEntities.Define())
            {
                return context.TenderBidders.FirstOrDefault(t => t.Id == Id);
            }
        }

        public TenderBidderQuote GetTenderBidderQuoteByItemId(Guid tenderBidderId, Guid orItemId)
        {
            using (var context = SCMSEntities.Define())
            {
                var tbq = context.TenderBidderQuotes.FirstOrDefault(t => t.TenderBidderId == tenderBidderId && t.OrderRequestItemId == orItemId);
                var item = tbq.OrderRequestItem.Item;
                return tbq;
            }
        }

        public List<Model.ShippingTermView> GetShippingTerms(Guid id)
        {
            using (var context = new SCMSEntities())
            {
                var shippingTerms = context.ShippingTerms.Where(p => p.CountryProgrammeId == id).OrderBy(s => s.Description).ToList();
                List<ShippingTermView> stList = new List<ShippingTermView>();
                foreach (var shippingTerm in shippingTerms)
                {
                    stList.Add(new ShippingTermView { Id = shippingTerm.Id, Description = shippingTerm.Description + " (" + shippingTerm.Name + ")" });
                }
                return stList;
            }
        }

        public List<Model.PaymentTerm> GetPaymentTerms(Guid id)
        {
            using (var context = new SCMSEntities())
            {
                return context.PaymentTerms.Where(p => p.CountryProgrammeId == id).OrderBy(p => p.Description).ToList();                
            }
        }

        public List<Model.TenderAnalysi> GetTenderAnalysesForEval(SystemUser currentUser)
        {
            List<TenderAnalysi> tenderAnalyses = new List<TenderAnalysi>();
            try
            {
                using (var context = SCMSEntities.Define())
                {
                    var taList = context.TenderAnalysis.Where(t => t.CountryProgrammeId == currentUser.Staff.CountrySubOffice.CountryProgrammeId && t.IsSubmitted == true && t.IsRejected == false && t.TenderEvaluators.Where(e => e.HasApproved == null && e.StaffId == currentUser.StaffId && e.Priority < 3).Count() > 0).ToList<TenderAnalysi>();
                    foreach (var ta in taList)
                    {
                        //If this is the first evaluator then add the ta to the list
                        var evaluator = context.TenderEvaluators.FirstOrDefault(e => e.TenderAnalysisId == ta.Id && e.Priority == 1 && e.StaffId == currentUser.StaffId);
                        if (evaluator != null)
                        {
                            tenderAnalyses.Add(ta);
                            continue;
                        }
                        //If this is the second evaluator, then first check that the first evaluator has evaluated/approved
                        evaluator = context.TenderEvaluators.FirstOrDefault(e => e.TenderAnalysisId == ta.Id && e.Priority == 2 && e.StaffId == currentUser.StaffId);
                        if (evaluator != null)
                        {
                            var firstEval = context.TenderEvaluators.FirstOrDefault(e => e.TenderAnalysisId == ta.Id && e.Priority == 1 && e.HasApproved.HasValue == true);
                            if (firstEval != null)
                            {
                                tenderAnalyses.Add(ta);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
            }
            return tenderAnalyses;
        }

        public List<Model.TenderAnalysi> GetTenderAnalysesForAuth(SystemUser currentUser)
        {
            List<TenderAnalysi> tenderAnalyses = new List<TenderAnalysi>();
            bool? firstEval = false, secondEval = false;
            try
            {                
                using (var context = SCMSEntities.Define())
                {
                    var taList = context.TenderAnalysis.Where(t => t.CountryProgrammeId == currentUser.Staff.CountrySubOffice.CountryProgrammeId && t.IsSubmitted == true && t.IsRejected == false && t.IsAuthorized != true && t.TenderEvaluators.Where(e => e.HasApproved != null).Count() > 0).ToList<TenderAnalysi>();
                    foreach (var ta in taList)
                    {
                        var te1 = ta.TenderEvaluators.FirstOrDefault(e => e.Priority == 1);
                        var te2 = ta.TenderEvaluators.FirstOrDefault(e => e.Priority == 2);
                        var te3 = ta.TenderEvaluators.FirstOrDefault(e => e.Priority == 3);
                        if (te3 == null || te3.StaffId != currentUser.StaffId)
                            continue;
                        if (te1 == null || te2 == null)
                            continue;
                        firstEval = te1.HasApproved;
                        secondEval = te2.HasApproved;
                        if (firstEval != null && secondEval != null)
                            tenderAnalyses.Add(ta);
                    }
                    return tenderAnalyses;
                }
            }
            catch (Exception ex)
            {
                return tenderAnalyses;
            }
        }

        public List<Model.Supplier> GetTenderBidderSuppliers(Guid taId)
        {
            try
            {
                using (var context = SCMSEntities.Define())
                {
                    return context.Suppliers.Where(s => s.TenderBidders.Where(t => t.TenderAnalysisId == taId).Count() > 0).OrderBy(s => s.Name).ToList<Supplier>();
                }
            }
            catch (Exception ex)
            {
                return new List<Supplier>();
            }
        }

        public List<Model.TenderEvaluator> GetTenderEvaluators(Guid tenderId)
        {
            try
            {
                using (var context = SCMSEntities.Define())
                {
                    var evaluators = context.TenderEvaluators.Where(t => t.TenderAnalysisId == tenderId).OrderBy(t => t.Priority).ToList();
                    foreach (var eval in evaluators)
                    {
                        var person = eval.Staff.Person;
                        var desg = eval.Staff.Designation;
                        var supplier = eval.Supplier;
                    }
                    return evaluators;
                }
            }
            catch (Exception ex)
            {
                return new List<TenderEvaluator>();
            }
        }

        public TenderEvaluator GetTenderEvaluatorByPriority(Guid tenderId, int priority)
        {
            using (var context = SCMSEntities.Define())
            {
                var evaluator = context.TenderEvaluators.FirstOrDefault(t => t.TenderAnalysisId == tenderId && t.Priority == priority);
                if (evaluator != null)
                {
                    var person = evaluator.Staff.Person;
                    var desg = evaluator.Staff.Designation;
                }
                return evaluator;
            }
        }

        public TenderEvaluator GetTenderEvaluatorById(Guid Id)
        {
            try
            {
                using (var context = SCMSEntities.Define())
                {
                    return context.TenderEvaluators.FirstOrDefault(t => t.Id == Id);
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// Get set priority 3 evaluator or authorizer of underlying order request if at all he/she exists in TA authorizers. 
        /// </summary>
        /// <param name="tenderId"></param>
        /// <returns></returns>
        public TenderEvaluator GetTenderAuthorizer(Guid tenderId)
        {
            try
            {
                Staff taAuthorizer = null;
                using (var context = SCMSEntities.Define())
                {
                    //Return set evaluator with Priority 3
                    var taEvaluator = context.TenderEvaluators.FirstOrDefault(t => t.TenderAnalysisId == tenderId && t.Priority == 3);
                    if (taEvaluator != null)
                    {
                        var person = taEvaluator.Staff.Person;
                        var desg = taEvaluator.Staff.Designation;
                        return taEvaluator;
                    }
                    //Return authorizer of underlying OR in case he/she exists in TA authorizers
                    var tender = context.TenderAnalysis.FirstOrDefault(t=>t.Id==tenderId);
                    var taApprovers = context.Approvers.Where(a => a.ActivityCode == NotificationHelper.taCode && a.ActionType == NotificationHelper.authorizationCode
                        && a.SystemUser.Staff.CountrySubOffice.CountryProgrammeId == tender.CountryProgrammeId).ToList();
                    foreach (var approver in taApprovers)
                    {
                        if (approver.SystemUser.StaffId == tender.OrderRequest.AuthorizedBy)
                        {
                            var person = approver.SystemUser.Staff.Person;
                            var desg = approver.SystemUser.Staff.Designation;
                            taAuthorizer = approver.SystemUser.Staff;
                            break;
                        }
                    }
                    //Return first TA Authorizer in list of TA Authorizers
                    if (taAuthorizer == null && taApprovers.Count > 0)
                    {
                        var person = taApprovers[0].SystemUser.Staff.Person;
                        var desg = taApprovers[0].SystemUser.Staff.Designation;
                        taAuthorizer = taApprovers[0].SystemUser.Staff;
                    }

                    //Set the authorizer we are going to return as the TenderEvaluator with Priority 3 for this TA
                    var taEval3 = new TenderEvaluator();
                    taEval3.Id = Guid.NewGuid();
                    taEval3.TenderAnalysisId = tender.Id;
                    taEval3.Priority = 3;
                    taEval3.StaffId = taAuthorizer.Id;
                    context.TenderEvaluators.AddObject(taEval3);
                    context.SaveChanges();
                    taEval3.Staff = taAuthorizer;

                    return taEval3;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public bool DeleteTenderAnalysis(Guid taId)
        {
            using (var context = SCMSEntities.Define())
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    try
                    {
                        //Delete Evaluators
                        var evaluators = context.TenderEvaluators.Where(e => e.TenderAnalysisId == taId).ToList();
                        context.TenderEvaluators.Delete(evaluators);
                        //Delete TenderBidderQuotes
                        var tbq = context.TenderBidderQuotes.Where(b => b.TenderBidder.TenderAnalysisId == taId).ToList();
                        context.TenderBidderQuotes.Delete(tbq);
                        //Delete TenderBidders
                        var tb = context.TenderBidders.Where(b => b.TenderAnalysisId == taId).ToList();
                        context.TenderBidders.Delete(tb);
                        //Delete TA
                        var ta = context.TenderAnalysis.FirstOrDefault(t => t.Id == taId);
                        context.TenderAnalysis.DeleteObject(ta);
                        if (context.SaveChanges() > 0)
                        {
                            scope.Complete();
                            return true;
                        }
                    }
                    catch(Exception ex)
                    {
                        scope.Dispose();
                        throw ex;
                    }
                }
            }
            return false;
        }


        public List<TenderAnalysisSummary> Find(List<Guid> ids)
        {
            List<TenderAnalysisSummary> tanalyses = new List<TenderAnalysisSummary>();

            using (var context = new SCMSEntities())
            {
                var results = from myTA in context.TenderAnalysis
                              where ids.Contains(myTA.Id)
                              select myTA;

                foreach (Model.TenderAnalysi tItem in results.ToList())
                {
                    TenderAnalysisSummary tmp = new TenderAnalysisSummary();
                    tmp.Id = tItem.Id;
                    tmp.RefNo = tItem.RefNumber;

                    tmp.OrderRefNumber = tItem.OrderRequest.RefNumber;

                    Staff prepBy = context.Staffs.SingleOrDefault(p => p.Id == tItem.PreparedBy);
                    Person ps = prepBy.Person;

                    tmp.PreparedBy = ps.FirstName + " " + ps.OtherNames;

                    if (tItem.IsAuthorized.HasValue && ((bool)tItem.IsAuthorized))
                    {
                        tmp.Status = "AU";
                        tmp.StatusDate = (DateTime)tItem.AuthorizedOn;
                    }                    
                    else if (tItem.IsRejected)
                    {
                        tmp.Status = "RJ";

                        if (tItem.AuthorizedOn.HasValue)
                        {
                            tmp.StatusDate = (DateTime)tItem.AuthorizedOn;
                        }
                    }
                    else if (tItem.IsSubmitted.HasValue && ((bool)tItem.IsSubmitted))
                    {
                        tmp.Status = "CR";
                        tmp.StatusDate = (DateTime)tItem.PreparedOn;
                    }
                    else
                    {
                        tmp.Status = "NEW";
                        tmp.StatusDate = (DateTime)tItem.PreparedOn;
                    }

                    tanalyses.Add(tmp);
                }

            }

            return tanalyses;
        }

    }
}
